import React, { Component } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Modal, Toast, ActivityIndicator } from 'antd-mobile';
import MyNavBar from 'components/navbar/index';
import PDFViewers from 'components/pdf-viewer/pdf-viewers';
import { checkUrl } from 'utils/utils';
import { ENTER_TYPE } from 'utils/Enum';
import { remoteLinkAddress } from 'utils/ip';
import { getSession, getIsDingTalk } from 'utils/utils';
import commonStyles from 'utils/common.less';
const alert = Modal.alert;

import style from './index.less';
import { recordEnterHistoryNum, backToOut } from '../../utils/utils';

const DEFAULT_MAX_SCALE = 1.3;
const DEFAULT_MIN_SCALE = 0.2;
const DEFAULT_ROOM_IN_SCALE = 1.05;
const DEFAULT_ROOM_OUT_SCALE = 0.95;

@connect(({ signTheSuccessModel }) => ({ signTheSuccessModel }))
class signatureViewer extends Component {
	constructor(props) {
		super(props);
		this.state = {
			// scale: (document.documentElement.clientWidth - 80) / 794,
			scale: (document.documentElement.clientWidth) / 795,
			pdfList: [],
		};
		this.viewerRef = '';
		this.maxScale = DEFAULT_MAX_SCALE;
		// this.minScale = DEFAULT_MIN_SCALE;
		this.minScale = (document.documentElement.clientWidth) / 795
		this.roomInScale = DEFAULT_ROOM_IN_SCALE;
		this.roomOutScale = DEFAULT_ROOM_OUT_SCALE;
	}

	//获取跳转页面的参数
	componentDidMount() {
		const {
			location: { query },
			dispatch
		} = this.props;
		const { Session, enterType, envelopeWsid, fileWsid, fileUrl } = query;
		//判断是否同一次登录，如果session不同，则把已经在localstorage里的数据清空
		const lastSession = localStorage.getItem('Session');
		if (enterType) {
			if (lastSession && lastSession !== Session && enterType == ENTER_TYPE.EXTERNAL) {
				// localStorage.clear();
				localStorage.setItem('enterHistoryNum', '');
				localStorage.setItem('isEnterPage', '')
			}
		}
		//记录返回页在history中的位置编号
		const isEnterPage = localStorage.getItem('isEnterPage') || 'yes';
		if (isEnterPage === 'yes') {
			recordEnterHistoryNum();
		}
		if (enterType === ENTER_TYPE.EXTERNAL) {
			localStorage.setItem('Session', Session);
			// localStorage.setItem('returnUrl', url);
			localStorage.setItem('envelopeWsid', envelopeWsid);
			localStorage.setItem('fileWsid', fileWsid);
			localStorage.setItem('fileUrl', fileUrl);
			if (envelopeWsid && Session && localStorage.getItem('returnUrl')) {
				if (fileWsid) {
					dispatch({
						type: 'signTheSuccessModel/save',
						payload: {
							pdfList: [{
								id: envelopeWsid,
								name: envelopeWsid,
								pdfSrc: `${remoteLinkAddress()}file/files/${fileWsid}?X-Requested-Session=${getSession()}`,
							}]
						},
					});
				}
				else {
					Toast.loading('加载中...', 0);
					this.getPDFList();
				}
			} else if (Session && fileUrl) {
				dispatch({
					type: 'signTheSuccessModel/save',
					payload: {
						pdfList: [
							{
								id: Session,
								name: Session,
								pdfSrc: `${remoteLinkAddress()}converter/converters/pdf-converter/json-convert/preview?X-Requested-Session=${Session}&url=${fileUrl}`,
							}
						]
					}
				})
			} else if (Session && fileWsid) {
				dispatch({
					type: 'signTheSuccessModel/save',
					payload: {
						pdfList: [{
							id: envelopeWsid,
							name: envelopeWsid,
							pdfSrc: `${remoteLinkAddress()}file/files/${fileWsid}?X-Requested-Session=${getSession()}`
						}]
					},
				});
			} else {
				alert('警告', '无法操作！', [{ text: '返回', onPress: () => backToOut() }]);
				return;
			}
		} else if (enterType == ENTER_TYPE.INTERIOR) {
			Toast.loading('加载中...', 0);
			this.getPDFList();
		} else {
			alert('警告', '无法操作！', [{ text: '返回', onPress: () => backToOut() }]);
			return;
		}
	}

	onBindPDFRef = (ref) => {
		this.viewerRef = ref;
	};

	getPDFList = () => {
		const { dispatch } = this.props;
		dispatch({
			type: 'signTheSuccessModel/getPDFList',
			payload: {
				fields: null,
				filters: null,
				sorts: null,
				offset: 0,
				limit: 1000,
			},
			callback: (status, msg) => {
				if (status === 'error') {
					Toast.fail(msg)
				} else {
					Toast.hide()
				}
			}
		})
	};

	setScale(scale, center = {
		top: document.documentElement.clientHeight / 2,
		left: document.documentElement.clientWidth / 2,
	}) {
		if (scale === this.state.scale) return;
		if (scale > this.maxScale) scale = this.maxScale;
		if (scale < this.minScale) scale = this.minScale;
		this.viewerRef.setScale(scale, center);
		this.setState({
			scale: scale
		})
	}

	onZoomIn = center => {
		this.setScale(this.state.scale * this.roomInScale, center);
	};

	//缩小事件
	onZoomOut = center => {
		this.setScale(this.state.scale * this.roomOutScale, center);
	};
	//设置缩放比例事件
	onScaleChange = (scale, center) => {
		this.setScale(scale, center);
	};


	render() {
		const { scale } = this.state;
		const backUrl = localStorage.getItem('returnUrl');
		const {
			signTheSuccessModel: { pdfList }
		} = this.props;
		const enterType = localStorage.getItem('enterType')
		let isExternal = false
		if (enterType == ENTER_TYPE.EXTERNAL) {
			isExternal = true
		}
		const isDingTalk = getIsDingTalk();

		// const contentContainer = style.contentContainer + ' ' + commonStyles.headerTop;
		const contentContainer = isDingTalk === 'true' ? style.contentContainer : style.contentContainer + ' ' + commonStyles.headerTop;
		return (
			<div className={style.pageContainer}>
				<MyNavBar title={'文件预览'} isExternal={true} />
				<div className={contentContainer}>
					{
						pdfList.length > 0 ?
						<PDFViewers
							onBindPDFRef={this.onBindPDFRef}
							scale={scale}
							docs={pdfList}
							onZoomIn={this.onZoomIn}
							onZoomOut={this.onZoomOut}
							onScaleChange={this.onScaleChange}
						/>
						:
						null 
					}
				</div>
			</div>
		);
	}
}

export default signatureViewer;
